<template>
  <view>
    <!-- 顶部计时器区域 -->
    <view class="time-display">
      <text class="fa fa-clock-o mr-2"></text>
      <text class="text-bold">活动进行中：</text>
      <text class="timer-number">{{ localTimer.days }}</text>天
      <text class="timer-number">{{ localTimer.hours }}</text>时
      <text class="timer-number">{{ localTimer.minutes }}</text>分
      <text class="timer-number">{{ localTimer.seconds }}</text>秒
    </view>

    <!-- 顶部报名倒计时及报名按钮 -->
    <view class="top-bar">
      <view class="countdown">
        <text class="fa fa-clock-o mr-2"></text>投票截止：
        <text class="text-bold">
          <text class="countdown-number">{{ localCountdown.days }}</text>天
          <text class="countdown-number">{{ localCountdown.hours }}</text>时
          <text class="countdown-number">{{ localCountdown.minutes }}</text>分
          <text class="countdown-number">{{ localCountdown.seconds }}</text>秒
        </text>
      </view>
      <button class="register-btn" :disabled="isVotingEnded">
        <text class="fa fa-pencil mr-2"></text>我要投票
      </button>
    </view>
  </view>
</template>

<script>
export default {
  props: {
    timer: {
      type: Object,
      default: () => ({
        days: 0,
        hours: 0,
        minutes: 0,
        seconds: 0
      })
    },
    countdown: {
      type: Object,
      default: () => ({
        days: 0,
        hours: 0,
        minutes: 0,
        seconds: 15
      })
    },
    isVotingEnded: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      localTimer: {...this.timer},
      localCountdown: {...this.countdown},
      timerInterval: null,
      countdownInterval: null,
      lastCloseTime: null, // 记录页面关闭时间
      savedCountdownSeconds: null, // 记录关闭页面时的倒计时总秒数
      totalCountdownSeconds: null // 记录新的倒计时总时长
    };
  },
  mounted() {
    // 恢复倒计时状态
    this.restoreCountdown();
    this.startTimer();
    this.startCountdown();

    // 监听页面关闭事件
    window.addEventListener('beforeunload', this.handleBeforeUnload);
  },
  beforeUnmount() {
    // 清理资源
    this.clearTimers();
    window.removeEventListener('beforeunload', this.handleBeforeUnload);
  },
  watch: {
    countdown: {
      handler(newVal) {
        this.localCountdown = {...newVal};
        this.totalCountdownSeconds =
          newVal.days * 86400 +
          newVal.hours * 3600 +
          newVal.minutes * 60 +
          newVal.seconds;
        localStorage.setItem('totalCountdownSeconds', this.totalCountdownSeconds);
        this.clearTimers();
        this.startTimer();
        this.startCountdown();
      },
      deep: true
    }
  },
  methods: {
    // 启动计时器
    startTimer() {
      this.timerInterval = setInterval(() => {
        // 更新计时器逻辑
        this.localTimer.seconds++;

        if (this.localTimer.seconds >= 60) {
          this.localTimer.seconds = 0;
          this.localTimer.minutes++;

          if (this.localTimer.minutes >= 60) {
            this.localTimer.minutes = 0;
            this.localTimer.hours++;

            if (this.localTimer.hours >= 24) {
              this.localTimer.hours = 0;
              this.localTimer.days++;
            }
          }
        }
        // 保存计时器状态到本地存储
        localStorage.setItem('timer', JSON.stringify(this.localTimer));
      }, 1000);
    },

    // 启动倒计时
    startCountdown() {
      this.countdownInterval = setInterval(() => {
        // 更新倒计时逻辑
        const totalSeconds =
          this.localCountdown.days * 86400 +
          this.localCountdown.hours * 3600 +
          this.localCountdown.minutes * 60 +
          this.localCountdown.seconds;

        if (totalSeconds > 0) {
          const newTotalSeconds = totalSeconds - 1;

          this.localCountdown.days = Math.floor(newTotalSeconds / 86400);
          const remainingSeconds = newTotalSeconds % 86400;

          this.localCountdown.hours = Math.floor(remainingSeconds / 3600);
          const remainingMinutes = remainingSeconds % 3600;

          this.localCountdown.minutes = Math.floor(remainingMinutes / 60);
          this.localCountdown.seconds = remainingMinutes % 60;
        } else {
          clearInterval(this.countdownInterval);
          this.clearTimers();
          // 清除本地存储的计时状态
          this.clearLocalStorage();
          this.$emit('countdownEnded');
        }
        // 保存倒计时状态到本地存储
        localStorage.setItem('countdown', JSON.stringify(this.localCountdown));
      }, 1000);
    },

    // 处理手动开始倒计时事件
    handleStartManualCountdown(newCountdown) {
      console.log('handleStartManualCountdown called'); 
      // 删除本地存储的计时数据
      console.log('Removing timer from local storage');
      localStorage.removeItem('timer');
      console.log('Removing countdown from local storage');
      localStorage.removeItem('countdown');
      localStorage.removeItem('lastCloseTime');
      localStorage.removeItem('savedCountdownSeconds');
      localStorage.removeItem('totalCountdownSeconds');

      // 更新本地倒计时数据
      this.localCountdown = newCountdown;
      this.localTimer = { days: 0, hours: 0, minutes: 0, seconds: 0 };
      this.totalCountdownSeconds =
        newCountdown.days * 86400 +
        newCountdown.hours * 3600 +
        newCountdown.minutes * 60 +
        newCountdown.seconds;
      localStorage.setItem('totalCountdownSeconds', this.totalCountdownSeconds);

      // 重新启动倒计时
      this.clearTimers();
      this.startTimer();
      this.startCountdown();

      // 重新存储计时数据
      console.log('Storing timer to local storage', this.localTimer);
      localStorage.setItem('timer', JSON.stringify(this.localTimer));
      console.log('Storing countdown to local storage', this.localCountdown);
      localStorage.setItem('countdown', JSON.stringify(this.localCountdown));

      // 触发倒计时重新开始事件
      this.$emit('countdownRestart');
    },

    // 清除计时器和倒计时器
    clearTimers() {
      if (this.timerInterval) clearInterval(this.timerInterval);
      if (this.countdownInterval) clearInterval(this.countdownInterval);
    },

    // 处理页面关闭事件
    handleBeforeUnload() {
      const totalSeconds =
        this.localCountdown.days * 86400 +
        this.localCountdown.hours * 3600 +
        this.localCountdown.minutes * 60 +
        this.localCountdown.seconds;
      this.savedCountdownSeconds = totalSeconds;
      this.lastCloseTime = Date.now();
      localStorage.setItem('lastCloseTime', this.lastCloseTime);
      localStorage.setItem('savedCountdownSeconds', this.savedCountdownSeconds);
    },

    // 恢复倒计时状态
    restoreCountdown() {
      const lastCloseTime = localStorage.getItem('lastCloseTime');
      const savedCountdownSeconds = localStorage.getItem('savedCountdownSeconds');
      const totalCountdownSeconds = localStorage.getItem('totalCountdownSeconds');
      if (lastCloseTime && savedCountdownSeconds && totalCountdownSeconds) {
        const elapsedSeconds = Math.floor((Date.now() - lastCloseTime) / 1000);
        const remainingSeconds = savedCountdownSeconds - elapsedSeconds;

        // 更新计时器
        this.addElapsedTimeToTimer(elapsedSeconds);

        if (remainingSeconds > 0) {
          this.localCountdown.days = Math.floor(remainingSeconds / 86400);
          const remainingSecs = remainingSeconds % 86400;
          this.localCountdown.hours = Math.floor(remainingSecs / 3600);
          const remainingMins = remainingSecs % 3600;
          this.localCountdown.minutes = Math.floor(remainingMins / 60);
          this.localCountdown.seconds = remainingMins % 60;

          // 更新计时器时长
          const timerSeconds = totalCountdownSeconds - remainingSeconds;
          this.localTimer.days = Math.floor(timerSeconds / 86400);
          const remainingTimerSeconds = timerSeconds % 86400;
          this.localTimer.hours = Math.floor(remainingTimerSeconds / 3600);
          const remainingTimerMinutes = remainingTimerSeconds % 3600;
          this.localTimer.minutes = Math.floor(remainingTimerMinutes / 60);
          this.localTimer.seconds = remainingTimerMinutes % 60;
          localStorage.setItem('timer', JSON.stringify(this.localTimer));
        } else {
          // 倒计时已结束
          this.clearTimers();
          this.clearLocalStorage();
          this.$emit('countdownEnded');
        }
      }
    },

    // 将流逝的时间添加到计时器
    addElapsedTimeToTimer(elapsedSeconds) {
      let totalSeconds =
        this.localTimer.days * 86400 +
        this.localTimer.hours * 3600 +
        this.localTimer.minutes * 60 +
        this.localTimer.seconds;

      totalSeconds += elapsedSeconds;

      this.localTimer.days = Math.floor(totalSeconds / 86400);
      const remainingSeconds = totalSeconds % 86400;

      this.localTimer.hours = Math.floor(remainingSeconds / 3600);
      const remainingMinutes = remainingSeconds % 3600;

      this.localTimer.minutes = Math.floor(remainingMinutes / 60);
      this.localTimer.seconds = remainingMinutes % 60;

      // 保存更新后的计时器状态到本地存储
      localStorage.setItem('timer', JSON.stringify(this.localTimer));
    },

    // 清除本地存储
    clearLocalStorage() {
      localStorage.removeItem('timer');
      localStorage.removeItem('countdown');
      localStorage.removeItem('lastCloseTime');
      localStorage.removeItem('savedCountdownSeconds');
      localStorage.removeItem('totalCountdownSeconds');
    }
  }
};
</script>

<style scoped>
/* 时间显示区域 */
.time-display {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  color: #555;
  padding: 8px 16px;
  font-size: 14px;
  border-bottom: 1px solid #eee;
}

.timer-number {
  display: inline-block;
  min-width: 20px;
  padding: 0 4px;
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
  margin: 0 2px;
  text-align: center;
  font-weight: bold;
  color: #ff3b30;
}

/* 顶部栏 */
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #ff3b30;
  color: #fff;
  padding: 12px 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.countdown {
  font-size: 14px;
  display: flex;
  align-items: center;
}

.text-bold {
  font-weight: bold;
}

.countdown-number {
  display: inline-block;
  min-width: 20px;
  padding: 0 4px;
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
  margin: 0 2px;
  text-align: center;
}

.register-btn {
  background-color: #fff;
  color: #ff3b30;
  border-radius: 4px;
  padding: 8px 16px;
  font-size: 14px;
  font-weight: bold;
  display: flex;
  align-items: center;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.register-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
}

.register-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}
</style>